package com.example.tcpNet;

import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author 郅占伟
 * @ClassName TestTCP
 * @Description TCP通信，需要先开服务端开始监听端口，在开启客户端发送数据
 * @Date 2024年05月15日
 * @Version: 1.0
 */
public class TestTCP {
    @Test
    public  void receiveData() {
        try (Socket socket = new Socket("127.0.0.1", 10086)) {
            System.out.println("客户端已打开，等待发送数据");

            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("hello,tcp world".getBytes());

            System.out.println("发送完毕，关闭客户端服务");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Test
    public  void sendData() {
        // 创建服务端 Socket 对象
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(10086);
            System.out.println("服务端已开启，等待客户端发送数据");

            // 监听连接
            Socket accept = serverSocket.accept();

            // 获取输入流，读取数据并显示
            InputStream inputStream = accept.getInputStream();
            byte[] bytes = new byte[1024];
            int length = inputStream.read(bytes);

            String client = new String(bytes, 0, length);
            System.out.println(client);

            System.out.println("已接收客户端发送的数据，服务端关闭");
            accept.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
